import {
  login,
  logout,
  getUserInfo,
  refreshToken
} from '@/api/admin/user'

import Utils from '@/utils'
import Storage from '@/plugins/store'

export default {
  state: {
    uid: '',
    name: '',
    avatar: '',
    token: Utils.getToken(),
    status: ''
  },
  mutations: {
    setUserId (state, id) {
      state.uid = id
    },
    setUserName (state, name) {
      state.name = name
    },
    setAvatar (state, avatar) {
      state.avatar = avatar
    },
    setStatus (state, status) {
      state.status = status
    },
    setToken (state, token) {
      state.token = token
      Utils.setToken(token)
    },
    clearAll (state) {
      state.token = ''
      Utils.removeToken()
      Storage.set('user', {})
    }
  },
  actions: {
    // 登录
    handleLogin ({
      commit
    }, data) {
      return new Promise((resolve, reject) => {
        login(data).then(res => {
          const data = res.data
          commit('setToken', data.token)
          resolve(res)
        }).catch(err => {
          reject(err)
        })
      })
    },
    // 退出登录
    handleLogOut ({
      commit
    }) {
      return new Promise((resolve, reject) => {
        logout().then((res) => {
          commit('clearAll')
          resolve(res)
        }).catch(err => {
          reject(err)
        })
      })
    },
    // 获取用户相关信息
    getUserInfo ({
      commit
    }) {
      return new Promise((resolve, reject) => {
        try {
          getUserInfo().then(res => {
            const data = res.data
            commit('setUserId', data.id)
            commit('setUserName', data.name)
            commit('setAvatar', data.avatar)
            commit('setStatus', data.status)
            Storage.set('user', data)
            resolve(res)
          }).catch(err => {
            reject(err)
          })
        } catch (error) {
          reject(error)
        }
      })
    },
    refreshToken ({
      commit
    }) {
      return new Promise((resolve, reject) => {
        try {
          refreshToken().then(res => {
            const data = res.data
            commit('setToken', data.access_token)
            resolve(res)
          })
        } catch (error) {
          reject(error)
        }
      })
    }
  }
}
